﻿import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

import FilUI

Window {

    id: window
    default property alias contentData              : layout_content.data
    property url windowIcon                         : "qrc:/res/image/favicon.ico.jpg"
    property int launchMode                         : FilWindowType.Standard
    property int blurRadius                         : 60
    property var argument                           : ({})
    property var background                         : com_background
    property double tintOpacity                     : 0.75
    property bool fixSize                           : false
    property bool fitsAppBarWindows                 : false
    property Component loadingItem                  : com_loading
    property Component customAppBar                 : com_custom_appbar
    property alias effect                           : frameless.effect
    readonly property alias effective               : frameless.effective
    readonly property alias availableEffects        : frameless.availableEffects
    property Item appBar                            : FilAppBar {
        title                                       : window.title
        height                                      : 35
        showClose                                   : window.showClose
        showMinimize                                : window.showMinimize
        showMaximize                                : window.showMaximize
        showStayTop                                 : window.showStayTop
        icon                                        : window.windowIcon
        customCom                                   : customAppBar
    }
    property color backgroundColor                  : {
        if (frameless.effective && active) {
            var backcolor
            if (frameless.effect === "dwm-blur") {
                backcolor = FilTools.withOpacity(FilTheme.windowActiveBackgroundColor, window.tintOpacity)
            } else {
                backcolor = "transparent"
            }
            return backcolor
        }
        if (active) {
            return FilTheme.windowActiveBackgroundColor
        }
        return FilTheme.windowBackgroundColor
    }
    property bool stayTop                           : false
    property bool showClose                         : true
    property bool showMinimize                      : true
    property bool showMaximize                      : true
    property bool showStayTop                       : true //false
    property bool autoMaximize                      : false
    property bool autoVisible                       : true
    property bool autoCenter                        : true
    property bool autoDestroy                       : true
    property bool useSystemAppBar                   : false
    property int __margins                          : 0
    property color resizeBorderColor                : {
        if (window.active) {
            return Qt.rgba(110/255, 110/255, 110/255, 1)
        }
        return Qt.rgba(167/255, 167/255, 167/255, 1)
    }
    property int resizeBorderWidth                  : 1
    property var _windowRegister
    property string _route
    property bool _hideShadow                       : false

    signal initArgument(var argument)
    signal lazyLoad()

    //
    color: FilTools.isSoftware() ? window.backgroundColor : "transparent"

    Component.onCompleted: {
        // useSystemAppBar = FilApp.useSystemAppBar
        if (!useSystemAppBar && autoCenter) {
            moveWindowToDesktopCenter()
        }
        fixWindowSize()
        initArgument(argument)
        if (window.autoVisible) {
            if (window.autoMaximize) {
                window.visibility = Window.Maximized
            } else {
                window.show()
            }
        }
        // loading blurRadius,tintOpacity from Settings
        blurRadius = SettingsHelper.getWindowBlurRadius(blurRadius)
        tintOpacity = SettingsHelper.getWindowOpacity(tintOpacity)
    }
    onVisibleChanged: {
        if (visible && d.isLazyInit) {
            window.lazyLoad()
            d.isLazyInit = false
        }
    }
    onBlurRadiusChanged: {
        SettingsHelper.saveWindowBlurRadius(blurRadius)
    }
    onTintOpacityChanged: {
        SettingsHelper.saveWindowOpacity(tintOpacity)
    }

    QtObject {
        id: d
        property bool isLazyInit: true
    }
    FilFrameless {
        id: frameless
        appbar                                      : window.appBar
        maximizeButton                              : appBar.buttonMaximize
        fixSize                                     : window.fixSize
        topmost                                     : window.stayTop
        disabled                                    : useSystemAppBar
        useSystemEffect                             : !FilTheme.blurBehindWindowEnabled
        onEffectiveChanged                          : {
            if (effective) {
                FilTheme.blurBehindWindowEnabled = false
            }
        }
        Component.onCompleted                       : {
            frameless.setHitTestVisible(appBar.layoutStandardbuttons)
        }
        Component.onDestruction                     : {
            frameless.onDestruction()
        }
    }

    Component {
        id: com_background
        Item {
            Rectangle {
                anchors.fill: parent
                color: window.backgroundColor
            }
            Image {
                id: img_back
                visible: false
                cache: false
                fillMode: Image.PreserveAspectCrop
                asynchronous: true
                Connections {
                    target: window
                    function onScreenChanged() {
                        img_back.updateLayout()
                    }
                }
                Connections {
                    target: FilTheme
                    function onDesktopImagePathChanged() {
                        timer_update_image.restart()
                    }
                    function onBlurBehindWindowEnabledChanged() {
                        if (FilTheme.blurBehindWindowEnabled) {
                            img_back.source = FilTools.getUrlByFilePath(FilTheme.desktopImagePath)
                        } else {
                            img_back.source = ""
                        }
                    }
                }
                Timer {
                    id: timer_update_image
                    interval: 150
                    onTriggered: {
                        img_back.source = ""
                        img_back.source = FilTools.getUrlByFilePath(FilTheme.desktopImagePath)
                    }
                }
                function updateLayout() {
                    var geometry = FilTools.desktopAvailableGeometry(window)
                    img_back.width = geometry.width
                    img_back.height = geometry.height
                    img_back.sourceSize = Qt.size(img_back.width, img_back.height)
                }
                Component.onCompleted: {
                    img_back.updateLayout()
                    source = FilTools.getUrlByFilePath(FilTheme.desktopImagePath)
                }
            }
            FilAcrylic {
                anchors.fill: parent
                target: img_back
                tintOpacity: window.tintOpacity
                blurRadius: window.blurRadius
                visible: /*window.active &&*/ FilTheme.blurBehindWindowEnabled
                tintColor: Qt.rgba(1, 1, 1, 1)
                targetRect: Qt.rect(window.x - window.screen.virtualX,
                                    window.y - window.screen.virtualY,
                                    window.width,
                                    window.height)
            }
        }
    }

    Component {
        id: com_app_bar
        Item {
            data: window.appBar
            Component.onCompleted: {
                window.appBar.width = Qt.binding(function() {
                    return this.parent.width
                })
            }
        }
    }

    Component {
        id: com_custom_appbar
        Item { }
    }

    Component {
        id: com_loading
        Popup {
            id: popup_loading
            focus: true
            width: window.width
            height: window.height
            anchors.centerIn: Overlay.overlay
            closePolicy: {
                if (cancel) {
                    return Popup.CloseOnEscape | Popup.CloseOnPressOutside
                }
                return Popup.NoAutoClose
            }
            Overlay.modal: Item {}
            onVisibleChanged: {
                if (!visible) {
                    loader_loading.sourceComponent = undefined
                }
            }
            padding: 0
            opacity: 0
            visible:true
            Behavior on opacity {
                SequentialAnimation {
                    PauseAnimation {
                        duration: 83
                    }
                    NumberAnimation{
                        duration:  167
                    }
                }
            }
            Component.onCompleted: {
                opacity = 1
            }
            background: Rectangle {
                color:"#44000000"
            }
            contentItem: Item {
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        if (cancel) {
                            popup_loading.visible = false
                        }
                    }
                }
                ColumnLayout {
                    spacing: 8
                    anchors.centerIn: parent
                    FilProgressRing {
                        Layout.alignment: Qt.AlignHCenter
                    }
                    FilText {
                        text:loadingText
                        Layout.alignment: Qt.AlignHCenter
                    }
                }
            }
        }
    }

    Component {
        id: com_border
        Rectangle {
            color: "transparent"
            border.width: window.resizeBorderWidth
            border.color: window.resizeBorderColor
        }
    }

    Item {
        id: layout_container
        anchors.fill: parent
        anchors.margins: window.__margins
        Loader {
            anchors.fill: parent
            sourceComponent: background
            Component.onDestruction: sourceComponent = undefined
        }
        Loader {
            id:loader_app_bar
            anchors {
                top: parent.top
                left: parent.left
                right: parent.right
            }
            height: {
                if(window.useSystemAppBar){
                    return 0
                }
                return window.fitsAppBarWindows ? 0 : window.appBar.height
            }
            sourceComponent: window.useSystemAppBar ? undefined : com_app_bar
            Component.onDestruction: sourceComponent = undefined
        }
        Item {
            id: layout_content
            anchors {
                top: loader_app_bar.bottom
                left: parent.left
                right: parent.right
                bottom: parent.bottom
            }
            clip: true
        }
        Loader {
            id: loader_loading
            property string loadingText
            property bool cancel: false
            anchors.fill: parent
            Component.onDestruction: sourceComponent = undefined
        }
        FilInfoBar {
            id: info_bar
            root: layout_container
        }
        Loader {
            id: loader_border
            anchors.fill: parent
            sourceComponent: {
                if (window.useSystemAppBar ||
                    FilTools.isWin() ||
                    window.visibility === Window.Maximized ||
                    window.visibility === Window.FullScreen) {
                    return undefined
                }
                return com_border
            }
            Component.onDestruction: sourceComponent = undefined
        }
    }
    function hideLoading() {
        loader_loading.sourceComponent = undefined
    }
    function showSuccess(text, duration, moremsg) {
        return info_bar.showSuccess(text, duration, moremsg)
    }
    function showInfo(text, duration, moremsg) {
        return info_bar.showInfo(text, duration, moremsg)
    }
    function showWarning(text, duration, moremsg) {
        return info_bar.showWarning(text, duration, moremsg)
    }
    function showError(text, duration, moremsg) {
        return info_bar.showError(text, duration, moremsg)
    }
    function clearAllInfo() {
        return info_bar.clearAllInfo()
    }
    function moveWindowToDesktopCenter() {
        var availableGeometry = FilTools.desktopAvailableGeometry(window)
        window.setGeometry((availableGeometry.width-window.width)/2+Screen.virtualX,(availableGeometry.height-window.height)/2+Screen.virtualY,window.width,window.height)
    }
    function fixWindowSize(){
        if(fixSize){
            window.maximumWidth =  window.width
            window.maximumHeight =  window.height
            window.minimumWidth = window.width
            window.minimumHeight = window.height
        }
    }
    function setResult(data){
        if(_windowRegister){
            _windowRegister.setResult(data)
        }
    }
    function showMaximized(){
        frameless.showMaximized()
    }
    function showMinimized(){
        frameless.showMinimized()
    }
    function showNormal(){
        frameless.showNormal()
    }
    function showLoading(text = "",cancel = true){
        if(text===""){
            text = qsTr("Loading...")
        }
        loader_loading.loadingText = text
        loader_loading.cancel = cancel
        loader_loading.sourceComponent = com_loading
    }
    function setHitTestVisible(val){
        frameless.setHitTestVisible(val)
    }
    function deleteLater(){
        FilTools.deleteLater(window)
    }
    function containerItem(){
        return layout_container
    }
}
